<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hosts Group</title>
    <link rel="icon" type="image/svg+xml" href="favicon.svg"/>
    <link rel="stylesheet" href="main.css"/>
    <link rel="stylesheet" href="msgTips.css"/>

    <link rel="stylesheet" href="lib/codemirror.css">
    <script src="lib/codemirror.js"></script>

    <link rel="stylesheet" href="theme/material.css">
    <script src="mode/nginx/nginx.js"></script>
    <script src="mode/hosts/hosts.js"></script>
</head>
<body>

<main>
    <div class="group-list">
        <div id="groupList"></div>
    </div>
    <textarea id="content"></textarea>
</main>

<script src="main.js"></script>
<script>
    let editor;

    function fillParam(params) {
        if (!params.time) {
            params.time = 1500;
        }

        if (!params.type) {
            params.type = 'tips'
        }
    }

    function msgTips(params) {
        fillParam(params)
        if (params.type === 'tips') {
            params.message = '😀 ' + params.message;
        } else if (params.type === 'error') {
            params.message = '😅 ' + params.message
        }

        let el = document.createElement("div");
        el.setAttribute("class", "web-toast" + ' type-' + params.type);
        el.innerHTML = params.message;
        document.body.appendChild(el);
        el.classList.add("fadeIn");
        setTimeout(function () {
            el.classList.remove("fadeIn");
            el.classList.add("fadeOut");
            /*监听动画结束，移除提示信息元素*/
            el.addEventListener("animationend", function () {
                document.body.removeChild(el);
            });
            el.addEventListener("webkitAnimationEnd", function () {
                document.body.removeChild(el);
            });
        }, params.time)
    }

    function getFile(fileName) {
        for (let i = 0; i < totalItem.length; i++) {
            document.getElementById("group-item-" + totalItem[i]).style.backgroundColor = 'white';
        }

        get(basePath + 'getFile?file=' + fileName, function (req) {
            localStorage.setItem(curFileKey, fileName)
            document.getElementById("group-item-" + fileName).style.backgroundColor = '#b3e19d';

            let respTxt = req.responseText;//获取到json字符串，还需解析
            let data = JSON.parse(respTxt);

            if (data.code === 0) {
                editor.setValue(data.data.content)
                document.getElementById("group-item-check-" + fileName).checked = data.data.use
            } else {
                alert(fileName + "not exist")
            }
        })
    }

    function queryCurrent() {
        get(basePath + 'currentHosts', function (req) {
            clearSelect();
            for (let i = 0; i < totalItem.length; i++) {
                document.getElementById("group-item-" + totalItem[i]).style.backgroundColor = 'white';
            }

            let respTxt = req.responseText;
            let data = JSON.parse(respTxt);
            if (data.code === 0) {
                editor.setValue(data.data)
            } else {
                alert("current hosts not exist")
            }
        })
    }

    function switchGroupState(fileName) {
        get(basePath + 'switch?file=' + fileName, function (req) {
            let respTxt = req.responseText;
            let data = JSON.parse(respTxt);
            if (data.code === 0) {
                let checked = data.data;
                document.getElementById("group-item-check-" + fileName).checked = checked
                msgTips({message: fileName + (checked ? " 已启用" : " 已禁用"), time: 500})
            } else {
                alert("current hosts not exist")
            }
        })
    }

    function saveFile() {
        let contentObj = editor.getValue();

        let finalFileName
        let newFileName = document.getElementById("group-item-new-label").value;
        let isUse = document.getElementById("group-item-new-check").checked;
        if (!newFileName || newFileName.length <= 0) {
            finalFileName = localStorage.getItem(curFileKey)
            if (!finalFileName) {
                msgTips({message: "未选中分组", type: 'error'})
                return
            }

            isUse = document.getElementById("group-item-check-" + finalFileName).checked;
        } else {
            finalFileName = newFileName
        }
        if (finalFileName.length <= 0) {
            msgTips({message: "未选中分组", type: 'error'})
            return
        }

        let fileItem = {
            name: finalFileName,
            content: contentObj,
            use: isUse
        };
        if (contentObj === "") {
            msgTips({message: "未选中分组", type: 'error'})
            return
        }
        console.log('post', fileItem)

        let httpRequest = new XMLHttpRequest();
        httpRequest.open("POST", basePath + 'postFile', true);
        httpRequest.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
        httpRequest.send(JSON.stringify(fileItem))
        httpRequest.onreadystatechange = () => {
            if (httpRequest.readyState === 4 && httpRequest.status === 200) {
                let data = JSON.parse(httpRequest.responseText);
                if (data.code !== 0) {
                    alert(data.msg)
                    return
                }
                if (newFileName) {
                    window.location.reload()
                }
                // console.log(data);
                document.getElementById("group-item-new-check").checked = false
            }
        }
        msgTips({
            message: finalFileName + " 保存成功",
            time: 700
        })
    }

    function clearSelect() {
        localStorage.removeItem(curFileKey)
    }

    function listGroups() {
        totalItem = []
        get(basePath + 'listFile', function (rsp) {
            // console.log('list: ', datum)
            let listEle = document.getElementById("groupList");
            let respTxt = rsp.responseText;//获取到json字符串，还需解析
            let data = JSON.parse(respTxt);
            listEle.innerHTML += '<div class="group-item" onclick="clearSelect()">' +
                '<input type="checkbox" id="group-item-new-check"/>' +
                '<input id="group-item-new-label" maxlength="30" minlength="1" type="text" class="new-input" placeholder="create new"/>' +
                '</div>';

            if (!data.data) {
                return
            }
            data.data.forEach(oneFile => {
                let name = oneFile.name;
                totalItem.push(name)
                listEle.innerHTML += '<div class="group-item" id="group-item-' + name + '">' +
                    '<input type="checkbox" id="group-item-check-' + name +
                    '" onclick="switchGroupState(\'' + name + '\')" ' + (oneFile.use ? 'checked' : '') + '/>' +
                    '<span id="group-item-label-' + name + '" onclick="getFile(\'' + name + '\')">' + name + '</span>' +
                    '</div>';
            })
        })
    }

    function bindKeyDown() {
        document.onkeydown = function (event) {
            // Ctrl S
            if (event.ctrlKey === true && event.key === 's') {
                event.preventDefault();
                saveFile();
            }

            // Ctrl D
            if (event.ctrlKey === true && event.key === 'd') {
                event.preventDefault();
                msgTips({message: "显示当前 hosts", time: 800})
                queryCurrent();
            }
        }
    }

    function initEditor() {
        get(basePath + 'queryMode', function (rsp) {
            let respTxt = rsp.responseText;//获取到json字符串，还需解析
            let data = JSON.parse(respTxt);
            editor = CodeMirror.fromTextArea(document.getElementById("content"), {
                mode: data.data,
                lineNumbers: true,
                theme: 'material'
            });
        })

    }

    listGroups();
    initEditor();
    bindKeyDown();
    localStorage.removeItem(curFileKey);
</script>
</body>

</html>